﻿namespace CRM_Perf_BenchMark
    {
    	using System;
    	using System.Collections.Generic;
        using Microsoft.VisualStudio.TestTools.WebTesting;
    	using System.Net;
    	using System.Text;
    	using System.Xml;
       	
		/// <summary>
		/// 1. Starts at Sales homepage
		/// 2. Click on Accounts
		/// 3. Click New
		/// 4. Add relevant data (name)
		/// 5. Click Save and Close
		/// </summary>

    	public class CreateNewAccount : CrmWebTest
    	{
    		public void CreateNewAccount_PreWebTest(object sender, PreWebTestEventArgs e)
    		{
                EntityRequest er = new EntityRequest();
                er.Type = EntityNames.Users;
                er.ReturnAs = EntityNames.Users;
                er.ParentID = EntityManager.Instance.OrgId;

                System.Collections.Hashtable userProps = new System.Collections.Hashtable();
                if (e.WebTest.Context.ContainsKey("UserRole"))
                {
                    userProps.Add("role", e.WebTest.Context["UserRole"]);
                    er.Props = userProps;
                }
                
                System.Collections.Hashtable Entities = EntityManager.Instance.GetEntities(er);

                user = (CRMEntity)Entities[EntityNames.Users];

                crmServer = user["CrmServer"];
                tokenKey = EntityManager.Instance.ReadTokenKey(user["organizationid"]);

                orgId = new Guid(user["organizationid"]);

                e.WebTest.UserName = user["domainName"];
                e.WebTest.Password = user["userpassword"];                
    		}
    		
            public void CreateNewAccount_PostWebTest(object sender, PostWebTestEventArgs e)
    		{
				try
				{
                    if (newAcctId != null)
                    {
                        Guid g = EntityManager.Instance.GetOwnerGuid(new Guid(user[EntityIDNames.User]), new Guid(user["OrganizationId"]));
						EntityManager.Instance.AddEntity(EntityNames.Accounts, g, new string[] { "OwningUser", "AccountID", "name" , "EntityManagerOwningUser"}, new string[] { user["systemuserid"], newAcctId, name, g.ToString() });
                    }
				}
				finally
				{
					EntityManager.Instance.FreeEntity(user);
				}
    		}

			private void NewAccount_ValidateResponse(object sender, ValidationEventArgs e)
			{
				string ID = null;

				int idIdx = e.Response.BodyString.IndexOf(newIdMarker);
				ID = e.Response.BodyString.Substring(idIdx + (CreateNewAccount.newIdMarker.Length), 36);
				try
				{
					ID = new Guid(ID).ToString();
				}
				catch (System.FormatException fe)
				{
					System.Diagnostics.Trace.WriteLine("Format exception: " + fe.ToString());
					e.IsValid = false;
					return;
				}	
				e.IsValid = true;
			}

    		public CreateNewAccount()
    		{
                WebRequest.RegisterPrefix("crm", new crmRequestFactory());
                GetContextHtml_Helper.PrimaryContact(out ctxt, out ctxt_formXml, out ctxt_formSubmitId);

                gridXml = GridXmlHelper.AccountPageViewRefresh(-1, myAccountsView, null);
    
    			this.Proxy = null;                
    			PreWebTest += new EventHandler<PreWebTestEventArgs>(CreateNewAccount_PreWebTest);
    			PostWebTest += new EventHandler<PostWebTestEventArgs>(CreateNewAccount_PostWebTest);
    		}
    
    		public override IEnumerator<WebTestRequest> GetRequestEnumerator()
    		{
				this.BeginTransaction("NavAccountHomepage");

                _root_homepage_aspx hp = new _root_homepage_aspx(user);
    			hp.etc = 1;
    			yield return (hp);

				this.EndTransaction("NavAccountHomepage");

 				this.BeginTransaction("CreateAccount");

                sfa_accts_edit_aspx dp = new sfa_accts_edit_aspx(user);
    			yield return (dp);

                referer = dp.lastResponse.ResponseUri.AbsoluteUri;

                _forms_FormScript_js_aspx formScript = new _forms_FormScript_js_aspx(user);
                formScript.etc = 1;
                formScript.FormType = "main";
                formScript.FormName = "crmForm";
                headerItem = new WebTestRequestHeader("referer", referer);
                formScript.Headers.Add(headerItem);
                yield return (formScript);
                
    			// if the Help and Assistance Pane is on and the user tabs through the fields of the account
    			// detail pane, they'll hit this (heavy) request when the tab into the 
    			// primay contact field.
    			if (ConfigSettings.Default.HelpAndAssistancePaneOn == "true")
    			{
  				    RelatedInformation.RelatedInformation ri = new RelatedInformation.RelatedInformation();
    				    WebTestRequest wtr = null;
        
  				    string formXml = ctxt_formXml;
  				    formXml = formXml.Replace("REPLACE_GUID", user["SystemUserId"].ToUpper());
  				    try { ri.GetContextHtml(ctxt, formXml, ctxt_formSubmitId); }
    				    catch (crmException x)
    				    {
    					    wtr = (CrmRequest)x.wtr;
                            wtr.Url = Utils.ReplaceServerName(wtr.Url, user);
    				    }
    				    yield return (wtr);
    			}

                dp = new sfa_accts_edit_aspx(user);
                name = Utils.GetRandomString(5, 30);
                dp.crmFormSubmitXml = EntityXmlHelper.GetCreateAccountXml(new Guid(user[EntityIDNames.User]), 8, name);

    			dp.crmFormSubmitMode = 1;
                dp.CrmFormUserModified = true;
    			dp.crmFormSubmitObjectType = 1;
    			dp.crmFormSubmitSecurity = 852023;
    			dp.crmFormSubmitOnline = 1;
                rpcInfo = Utils.GenerateWRPCToken(sfa_accts_edit_aspx.url, user, tokenKey);
                dp.CRMWRPCToken = rpcInfo.token;
                dp.CRMWRPCTokenTimeStamp = rpcInfo.timeStamp;
				dp.ValidateResponse += this.NewAccount_ValidateResponse;
    			yield return (dp);
    
    			//get the newly created account id out of the post reply
    			int idIdx = dp.lastResponse.BodyString.IndexOf(newIdMarker);
 			    string tempNewAcctId = dp.lastResponse.BodyString.Substring (idIdx+(CreateNewAccount.newIdMarker.Length), 36);
				newAcctId = new Guid(tempNewAcctId).ToString();

 			    AppGridWebService.AppGridWebService agws = new AppGridWebService.AppGridWebService();
    			WebTestRequest wtrRefresh = null;
                try { agws.Refresh(gridXml); }
    			catch (crmException x)
    			{
    				wtrRefresh = x.wtr;
                    wtrRefresh.Url = Utils.ReplaceServerName(wtrRefresh.Url, user);

                    string urlPath = wtrRefresh.Url.Remove(0, crmServer.Length);
                    urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                    rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                    headerItem = new WebTestRequestHeader();
                    headerItem.Name = "crmwrpctokentimestamp";
                    headerItem.Value = rpcInfo.timeStamp.ToString();
                    wtrRefresh.Headers.Add(headerItem);
                    headerItem = new WebTestRequestHeader();
                    headerItem.Name = "crmwrpctoken";
                    headerItem.Value = rpcInfo.token;
                    wtrRefresh.Headers.Add(headerItem);
                    wtrRefresh.Method = "Post";
    			}
    			yield return (wtrRefresh);
    
			    this.EndTransaction("CreateAccount");
    		}
    
   		    private static RelatedInformation.Context ctxt;
    		private static string ctxt_formXml;
    		private static string ctxt_formSubmitId;
            private const string newIdMarker = @"separator + ""id=";
    		private CRMEntity user;
		    private string newAcctId;            
            private string gridXml;
            private string crmServer;
            private string tokenKey;
            private static string myAccountsView = "00000000-0000-0000-00AA-000010001001";

            private Guid orgId;
            private string name;
            private WebTestRequestHeader headerItem;
            private WRPCInfo rpcInfo;
            private string referer;
        }
    }
